//
//  RegisterViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/2/27.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "RegisterViewController.h"
#import "registerView.h"
#import "RegisterConfirmViewController.h"
#import "SMSModelPack.h"
#import "ServerAddressModel.h"
#import "ETONEHttpClient.h"
//验证码倒计时
#import "WLButtonCountdownManager.h"
#import "CheckCodeModelPack.h"
@interface RegisterViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)RegisterView *rv;

@property(nonatomic,strong) NSString *identifyKey;

@end

@implementation RegisterViewController

-(instancetype)init{
    if (self = [super init]) {
        [self initialize];
    }
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    self.identifyKey = NSStringFromClass([self class]);
}


#pragma mark 初始化
-(void)loadView{
    [super loadView];
    self.rv = [[RegisterView alloc] initWithFrame:self.view.bounds];
    self.view = self.rv;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[WLButtonCountdownManager defaultManager] countdownTaskExistWithKey:self.identifyKey task:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"请填写注册信息";
    self.rv.userInteractionEnabled = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.rv.nextStepBtn addTarget:self action:@selector(nextStepBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.rv.phonoNumTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.rv.securityCodeNumTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    //发送验证码
    [self.rv.sendSMSBtn addTarget:self action:@selector(sendSMSBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.rv.phonoNumTf.delegate = self;
}


-(void)sendSMSBtnAction
{
    if (![AppTools validateMobile:self.rv.phonoNumTf.text]) {
        [self showFailedResultTips:@"请输入正确的手机号" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    SMSRequest *request = [[SMSRequest alloc] init];
    request.mobile = self.rv.phonoNumTf.text;
    request.smsType = @"0";
    NSDictionary *dic = [request mj_JSONObject];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/captcha/sendCodeA0200"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        NSLog(@"成功");
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [self dealSMSResponse:responseObject];
        }
        
    } FailedHandler:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}


-(void)dealSMSResponse:(id)responseObject
{
    
    //验证码发送成功  验证码输入框获取焦点
    [self.rv.securityCodeNumTf becomeFirstResponder];
    
    
    //发送成功一次   换账号、页面重进也需要60S之后才可以再次发送
    

    
    
    __weak __typeof(self) weakSelf = self;
    [[WLButtonCountdownManager defaultManager] scheduledCountDownWithKey:self.identifyKey timeInterval:60 countingDown:^(NSTimeInterval leftTimeInterval) {
        weakSelf.rv.sendSMSBtn.userInteractionEnabled = NO;
        [weakSelf.rv.sendSMSBtn setTitle:[NSString stringWithFormat:@"%@%@",@(leftTimeInterval),@"s"] forState:(UIControlStateNormal)];
        [weakSelf.rv.sendSMSBtn setTitleColor:[UIColor colorWithRed:150 / 255.0 green:196 / 255.0 blue:255 / 255.0 alpha:1] forState:(UIControlStateNormal)];
    } finished:^(NSTimeInterval finalTimeInterval) {
        [weakSelf.rv.sendSMSBtn setTitle:@"再次发送" forState:(UIControlStateNormal)];
        [weakSelf.rv.sendSMSBtn setTitleColor:[UIColor colorWithRed:49.0f/255.0f green:138.0f/255.0f blue:255.0f/255.0f alpha:1.0f] forState:(UIControlStateNormal)];
        weakSelf.rv.sendSMSBtn.userInteractionEnabled = YES;
    }];
    
}



-(void)nextStepBtnAction
{
    //检查验证码是否正确
    CheckCodeRequest *request = [[CheckCodeRequest alloc] init];
    request.mobile = self.rv.phonoNumTf.text;
    request.captcha = self.rv.securityCodeNumTf.text;
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/regist/verifyCaptcha"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [self dealCheckCode:responseObject];
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
    
    
    
    
}

-(void)dealCheckCode:(id)responseObject
{
    RegisterConfirmViewController *regVC = [[RegisterConfirmViewController alloc] init];
    regVC.phoneNumStr = self.rv.phonoNumTf.text;
    regVC.securityCodeNumStr = self.rv.securityCodeNumTf.text;
    [self.navigationController pushViewController:regVC animated:YES];
}

#pragma mark textField 监听
//输入框符合规则可以点击"下一步"
-(void)textFieldDidChange :(UITextField *)textField{

    //手机号输入框只能输入11位
    if (textField == self.rv.phonoNumTf) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    //验证码只能输入6位
    if (textField == self.rv.securityCodeNumTf) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
    }

    if (self.rv.securityCodeNumTf.text.length == 6 && [AppTools validateMobile:self.rv.phonoNumTf.text]) {
        //验证码输入的是6位  手机号输入框是手机号
        self.rv.nextStepBtn.userInteractionEnabled = YES;
        self.rv.nextStepBtn.backgroundColor = ETCONFIRMCOLOR;
    }else
    {
        self.rv.nextStepBtn.userInteractionEnabled = NO;
        self.rv.nextStepBtn.backgroundColor = ETCOMMONCOLOR;
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.rv.phonoNumTf resignFirstResponder];
    [self.rv.securityCodeNumTf resignFirstResponder];
}

@end
